package com.example.test.controller;

import com.example.test.common.ResultBody;
import com.example.test.query.ActivityModelQuery;
import com.example.test.vo.ActivityModelVO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * @author ：dengjue
 * @date ：Created in 2021/7/26 20:46
 * @description ： activiti模型Controller
 */
@Controller
@RequestMapping("/activiti/model")
@Slf4j
public class ActivitiModelController implements ModelDataJsonConstants{

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private RepositoryService repositoryService;

    /**
     * 创建模型
     */
    @PostMapping("/create")
    @ResponseBody
    public ResultBody create( ActivityModelVO modelVO) {
        try {
            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            RepositoryService repositoryService = processEngine.getRepositoryService();
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, modelVO.getName());
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, modelVO.getRevision());
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, modelVO.getDescription());
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(modelVO.getName());
            modelData.setKey(modelVO.getKey());
            modelData.setCategory(modelVO.getCategory());
            //保存模型   ACT_RE_MODEL 增加数据
            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
            modelVO.setId(modelData.getId());
        } catch (Exception e) {
            log.error("保存模型失败",e);
        }
        return ResultBody.success(modelVO);
    }

    /**
     * 编辑模型
     * @param modelId
     * @param response
     */
    @RequestMapping("/edit")
    public void edit(@RequestParam(value = "modelId")  String modelId, HttpServletResponse response) {
        try {
            Model model = repositoryService.getModel(modelId);
            if (model != null){
                response.sendRedirect("/activiti/modeler.html?modelId=" + modelId);
            }
        } catch (Exception e) {
            log.error("模型id不存在",e);
        }
    }


    /**
     * 保存模型
     * @param modelId
     * @param values
     */
    @RequestMapping(value="/{modelId}/save", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.OK)
    public void saveModel(@PathVariable String modelId, @RequestParam MultiValueMap<String, String> values) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            modelJson.put(MODEL_NAME, values.getFirst("name"));
            modelJson.put(MODEL_DESCRIPTION, values.getFirst("description"));
            model.setMetaInfo(modelJson.toString());
            model.setName(values.getFirst("name"));
            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(), values.getFirst("json_xml").getBytes("utf-8"));

            InputStream svgStream = new ByteArrayInputStream(values.getFirst("svg_xml").getBytes("utf-8"));
            TranscoderInput input = new TranscoderInput(svgStream);

            PNGTranscoder transcoder = new PNGTranscoder();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);

            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
        } catch (Exception e) {
            log.error("Error saving model", e);
            throw new ActivitiException("Error saving model", e);
        }
    }


    /**
     * 模型 发布  -- 工作流模型表   ACT_RE_PROCDEF ;  工作流业务表  ACT_RE_DEPLOYMENT  ; 新增数据
     * 更新 ACT_RE_MODEL
     * @param modelId
     * @return
     */
    @PostMapping("/deploye")
    @ResponseBody
    public ResultBody deploye(@RequestParam("modelId") String modelId){
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper()
                    .readTree(repositoryService.getModelEditorSource(modelData.getId()));
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            String processName = modelData.getName() + ".bpmn20.xml";

            // 每次发布都增加一条发布记录
            Deployment deployment = repositoryService.createDeployment()
                    .name(modelData.getName())
                    .category(modelData.getCategory())
                    .addString(processName, new String(bpmnBytes))
                    .enableDuplicateFiltering()
                    .deploy();

            // 更新 ACT_RE_MODEL表的DeploymentId
            modelData.setDeploymentId(deployment.getId());
            repositoryService.saveModel(modelData);
            return ResultBody.success("流程发布成功");
        } catch (Exception e) {
            log.error("流程发布失败",e);
        }
        return ResultBody.fail("流程发布失败");
    }


    /**
     * 获取模型
     * @param modelId
     * @return
     */
    @GetMapping(value="/{modelId}/json", produces = "application/json")
    @ResponseBody
    public ObjectNode getEditorJson(@PathVariable String modelId) {
        ObjectNode modelNode = null;
        Model model = repositoryService.getModel(modelId);
        if (model != null) {
            try {
                if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                    modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
                } else {
                    modelNode = objectMapper.createObjectNode();
                    modelNode.put(MODEL_NAME, model.getName());
                }
                modelNode.put(MODEL_ID, model.getId());
                ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(
                        new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
                modelNode.put("model", editorJsonNode);

            } catch (Exception e) {
                log.error("Error creating model JSON", e);
                throw new ActivitiException("Error creating model JSON", e);
            }
        }
        return modelNode;
    }


    /**
     * 导出model的xml文件
     */
    @GetMapping(value = "export/{modelId}")
    public void export(@PathVariable("modelId") String modelId, HttpServletResponse response) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
            BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
            byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);
            ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
            IOUtils.copy(in, response.getOutputStream());
            String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.flushBuffer();
        } catch (Exception e) {
            log.error("导出model的xml文件失败：modelId={}", modelId, e);
        }
    }

    /**
     * 模型删除
     * @param modelId
     * @return
     */
    @GetMapping(value = "delete/{modelId}")
    @ResponseBody
    public ResultBody delete(@PathVariable("modelId") String modelId) {
        Model model = repositoryService.getModel(modelId);
        repositoryService.deleteModel(modelId);
        if (StringUtils.isNotBlank(model.getDeploymentId())){
            repositoryService.deleteDeployment(model.getDeploymentId(),true);
        }
        return ResultBody.success("删除成功");
    }


    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("/activitiModel");
        return mv;
    }

    @GetMapping("/list")
    @ResponseBody
    public ResultBody list(ActivityModelQuery query){
        Integer offset = (query.getPageNum() - 1) * query.getPageSize();
        List<Model> list = repositoryService.createModelQuery().orderByCreateTime().desc()
                .listPage(offset,query.getPageSize());
        PageInfo pageInfo = new PageInfo(list);
        long total = repositoryService.createModelQuery().count();
        pageInfo.setTotal(total);
        return ResultBody.success(pageInfo);
    }
}
